<template>
  <div class="app-container">
    <div class="header-bar">
      <el-button
          type="primary"
          icon="ArrowLeft"
          @click="handleBack"
          class="back-btn"
      >
        返回
      </el-button>
      <h2 class="page-title">运动记录管理</h2>
    </div>

    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <!-- 新增记录按钮 -->
      <el-form-item class="action-button">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          新增记录
        </el-button>
        <el-button type="info" icon="InfoFilled" @click="showCaloriesTable = true" class="diet-btn">
          热量参考表
        </el-button>
      </el-form-item>

      <!-- 运动类型查询 -->
      <el-form-item label="运动类型" prop="sportType">
        <el-input
            v-model="queryParams.sportType"
            placeholder="请输入运动类型"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <!-- 日期范围查询 -->
      <el-form-item label="记录日期" prop="dateRange">
        <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 320px"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="query-actions">
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="sportList">
      <el-table-column label="记录日期" width="180">
        <template #default="scope">
          {{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column label="运动类型" prop="sportType" align="center"/>
      <el-table-column label="时长(分钟)" prop="duration" align="center">
  <template #default="scope">
    <el-tooltip 
      effect="light"
      placement="top"
      :content="healthAdviceMap.duration"
      v-if="abnormalFlags(scope.row).duration"
    >
      <span :class="{ 'abnormal-cell': abnormalFlags(scope.row).duration }">
        {{ scope.row.duration }}
      </span>
    </el-tooltip>
    <span v-else>{{ scope.row.duration }}</span>
  </template>
</el-table-column>
      <el-table-column label="距离(米)" prop="distance" align="center">
  <template #default="scope">
    <el-tooltip 
      effect="light"
      placement="top"
      :content="healthAdviceMap.distance"
      v-if="abnormalFlags(scope.row).distance"
    >
      <span :class="{ 'abnormal-cell': abnormalFlags(scope.row).distance }">
        {{ scope.row.distance }}
      </span>
    </el-tooltip>
    <span v-else>{{ scope.row.distance }}</span>
  </template>
</el-table-column>
      <el-table-column label="消耗卡路里" prop="calories" align="center">
  <template #default="scope">
    <el-tooltip 
      effect="light"
      placement="top"
      :content="healthAdviceMap.calories"
      v-if="abnormalFlags(scope.row).calories"
    >
      <span :class="{ 'abnormal-cell': abnormalFlags(scope.row).calories }">
        {{ scope.row.calories }}
      </span>
    </el-tooltip>
    <span v-else>{{ scope.row.calories }}</span>
  </template>
</el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 表单弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="运动类型" prop="sportType">
          <el-input
              v-model="form.sportType"
              placeholder="请输入运动类型"
              clearable
              :maxlength="20"
              show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时长(分钟)" prop="duration">
              <el-input-number
                  v-model="form.duration"
                  :min="1"
                  :max="600"
                  :precision="1"
                  controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="距离(米)" prop="distance">
              <el-input-number
                  v-model="form.distance"
                  :min="0"
                  :max="100000"
                  :precision="2"
                  controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="消耗卡路里" prop="calories">
          <el-input-number
              v-model="form.calories"
              :min="1"
              :max="5000"
              :precision="0"
              controls-position="right"
          />
        </el-form-item>

        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
              v-model="form.recordDate"
              type="date"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              placeholder="选择记录日期"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 热量参考弹窗 -->
    <el-dialog title="运动热量参考表" v-model="showCaloriesTable" width="70%">
      <el-table :data="caloriesData" border>
        <el-table-column prop="name" label="运动类型" width="180"/>
        <el-table-column prop="calories" label="消耗量(卡/半小时)"/>
        <el-table-column prop="note" label="注意事项"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { listSport, addSport, updateSport, delSport, getSport } from '@/api/healthSys/sport'
import {useStore} from "vuex";
import {addRecords, getRecords, updateRecords} from "@/api/healthSys/records.js";

const router = useRouter()
const { proxy } = getCurrentInstance()

// 响应式数据
const loading = ref(false)
const open = ref(false)
const title = ref('')
const sportList = ref([])
const total = ref(0)
const store = useStore() // 新增
const currentUserId = ref(null)
const showCaloriesTable = ref(false)
const caloriesData = reactive([
  {name: '田径', calories: 450, note: '可使人体全身得到锻炼'},
  {name: '篮球', calories: 250, note: '可增强灵活性，加强心肺功能'},
  {name: '自行车', calories: 330, note: '对心肺、腿十分有利'},
  {name: '骑马', calories: 175, note: '有益于大腿和意志的锻炼'},
  {name: '滑水', calories: 240, note: '对整个躯体、四肢肌肉和平衡能力有很好的锻炼作用'},
  {name: '高尔夫球', calories: 125, note: '它的锻炼效果来自时需要的长途跋涉和击球动作。如能持之以恒，对保持线条优美极为有利'},
  {name: '慢跑', calories: 300, note: '有益于心肺和血液循环。跑的路程越长，消耗的热量越大'},
  {name: '散步', calories: 75, note: '对心肺功能的增强有益，它能改善血液循环，活动关节和有助于减肥'},
  {name: '滑旱冰', calories: 175, note: '可增强全身灵活性和部力量'},
  {name: '跳绳', calories: 400, note: '这是一项健美运动，可改善人的姿态。三十五岁以上的人跳绳不可过于激烈'},
  {name: '壁球', calories: 300, note: '可锻炼两腿灵活性，可减肥，可增加速度能力。但心肺功能较差者不宜从事这项运动'},
  {name: '网球', calories: 220, note: '这是项激烈运动，它能够锻炼心肺功能，锻炼灵活性'},
  {name: '乒乓球', calories: 180, note: '属全身运动，有益于心肺，可锻炼重心的移动和协调性'},
  {name: '排球', calories: 175, note: '主要增强灵活性、弹跳力和体力，有益于心肺'},
  {name: '足球', calories: 220, note: '属全身运动，有益于心肺，可锻炼重心的移动和协调性'},
  {name: '羽毛球', calories: 200, note: '属全身运动，有益于心肺，可锻炼重心的移动和协调性'},  
  {name: '高尔夫球', calories: 125, note: '它的锻炼效果来自时需要的长途跋涉和击球动作。如能持之以恒，对保持线条优美极为有利'},
  {name: '游泳', calories: 240, note: '对整个躯体、四肢肌肉和平衡能力有很好的锻炼作用'},
  {name: '瑜伽', calories: 200, note: '它的锻炼效果来自时需要的长途跋涉和击球动作。如能持之以恒，对保持线条优美极为有利'},
  {name: '普拉提', calories: 300, note: '有益于心肺和血液循环。跑的路程越长，消耗的热量越大'},
  {name: '舞蹈', calories: 150, note: '对心肺、腿十分有利'},
  {name: '瑜伽', calories: 200, note: '有益于心肺和血液循环。跑的路程越长，消耗的热量越大'},
])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 12,
  userId: null,
  sportType: null,      // 新增运动类型参数
  orderByColumn: 'record_date', // 数据库字段名
  isAsc: 'desc' // 降序排列
})

// 表单数据
const form = reactive({
  sportId: null,
  userId: null,
  sportType: null,
  duration: null,
  distance: null,
  calories: null,
  recordDate: null
})

// 验证规则
const rules = {
  sportType: [{ required: true, message: '请选择运动类型', trigger: 'change' }],
  duration: [{ required: true, message: '请输入运动时长', trigger: 'blur' }],
  recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }]
}

// 健康建议映射
const healthAdviceMap = reactive({
  duration: '请注意，运动时长过长，可能导致过度疲劳，建议适当调整运动计划。',
  calories: '请注意，卡路里消耗过高，可能需要调整饮食或运动强度。',
  distance: '请注意，运动距离过长，可能对膝盖造成压力，建议适当调整运动计划。'
})

// 初始化数据
onMounted(() => {
  getList()
})

// 异常数据标记计算属性
const abnormalFlags = computed(() => (row) => {
  const { sportType, duration, distance, calories } = row
  return {
    duration: duration > 300, // 假设300分钟为异常时长阈值
    calories: calories > 3000, // 假设3000卡路里为异常卡路里阈值
    distance: distance > 10000 // 跑步距离超过10000米时预警
  }
})

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      orderByColumn: queryParams.orderByColumn,
      isAsc: queryParams.isAsc,
      beginDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1],
      sportType: queryParams.sportType
    }
    delete params.dateRange

    const res = await listSport(params)  // 修正方法名
    sportList.value = res.rows
    total.value = res.total
  } catch (error) {
    proxy.$modal.msgError('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryParams.dateRange = []
  queryParams.sportType = null  // 重置运动类型
  handleQuery()
}

// 新增记录
const handleAdd = () => {
  resetForm()
  open.value = true
  title.value = '新增运动记录'
}

// 修改记录
const handleUpdate = async (row) => {
  try {
    resetForm()
    const res = await getSport(row.sportId)
    Object.assign(form, res.data)
    open.value = true
    title.value = '修改运动记录'
  } catch (error) {
    proxy.$modal.msgError('数据加载失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await proxy.$refs.formRef.validate()

    // 确保携带用户ID
    const submitData = { ...form }
    console.log('提交数据:', JSON.stringify(form, null, 2)) // 打印完整数据

    if (form.sportId) {
      await updateSport(submitData)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addSport(submitData)
      proxy.$modal.msgSuccess('新增成功')
    }

    open.value = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await proxy.$modal.confirm(`确认删除 ${proxy.parseTime(row.recordDate)} 的记录？`)
    await delSport(row.sportId)
    getList()
    proxy.$modal.msgSuccess('删除成功')
  } catch (error) {
    // 取消删除不处理
  }
}

// 重置表单
const resetForm = () => {
  form.sportId = null
  form.sportType = null
  form.duration = null
  form.distance = null
  form.calories = null
  form.recordDate = null
  form.userId = currentUserId.value
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 取消操作
const cancel = () => {
  open.value = false
  resetForm()
}

const handleBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 32px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease;
}

.header-bar:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.back-btn {
  margin-right: 24px;
  padding: 12px 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  transform: translateX(-3px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
  background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.el-form {
  margin: 24px 0;
  padding: 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease;
}

.el-form:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.el-form-item {
  margin-bottom: 24px;
}

.action-button {
  margin-bottom: 32px;
}

.add-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
  border: none;
  color: white;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(0, 176, 155, 0.3);
}

.diet-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
  border: none;
  color: white;
}

.diet-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(0, 176, 155, 0.3);
}

.el-table {
  margin-top: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  transition: all 0.3s ease;
  line-height: 2.2;
  min-height: 480px;
  min-width: 120px;
}

.el-table__header th {
  background: #f8fafc;
  padding: 12px 0;
}

.el-table:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.el-table :deep(th) {
  font-weight: 600;
  color: #2c3e50;
  padding: 16px 8px;
}

.el-table :deep(td) {
  padding: 16px 8px;
  transition: all 0.3s ease;
}

.el-table :deep(tr:hover td) {
  background-color: #f8f9fa;
}

.el-button--primary {
  color: white;
  background: linear-gradient(135deg, #e74adf 0%, #68bde4 100%);
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.el-button--primary:active {
  transform: scale(0.98);
}

.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.el-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #ebeef5;
  padding: 24px 32px;
}

.el-dialog__title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.el-dialog__body {
  padding: 32px;
}

.el-input-number,
.el-date-editor {
  width: 100%;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-input-number:hover,
.el-date-editor:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.dialog-footer {
  padding: 16px 32px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.dialog-footer .el-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.dialog-footer .el-button:active {
  transform: scale(0.98);
}

.dialog-footer .el-button:hover {
  transform: translateY(-1px);
}

.pagination-container {
  margin-top: 32px;
  text-align: center;
  padding: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
}

@media screen and (max-width: 992px) {
  .el-date-picker {
    width: 100% !important;
  }
}

@media screen and (max-width: 768px) {
  .header-bar {
    padding: 16px 20px;
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .back-btn {
    margin: 0 0 16px 0;
  }

  .el-form {
    padding: 20px;
  }

  .el-form-item__content {
    flex-wrap: wrap;
  }

  .el-button {
    margin-top: 8px;
    width: 100%;
  }
  
  .el-dialog {
    margin: 10px !important;
    width: calc(100% - 20px) !important;
  }
}

.el-dialog__body {
  padding: 20px;
}
.el-table--border {
  margin-top: 15px;
}

.abnormal-cell {
  background-color: #ff4d4f; /* 红色背景 */
  color: white; /* 白色文字 */
  animation: blink 1s infinite; /* 闪烁动画 */
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
